import React, { Component } from "react";
import { View, Text, TouchableOpacity, ScrollView } from "react-native";
import NavBarConfig from "../modules/NavBar";
import { RECORDS, BGT_HISTORY, CREDIT_HISTORY } from "../../config/Api";
import http from "../../util/http";
import moment from "moment";
import { isScrollBottom } from "../../util/util";
import flowDetailStyles from "../../style/pages/flowDetail";

// 0x01增加 0x02减少 0x11缴存 0x22购买BGT 0x42提取 0x81清算赎回 不填不过滤
const filters = {
  1: [
    {
      id: 0x01,
      msg: "增加"
    },
    {
      id: 0x02,
      msg: "减少"
    },
    {
      id: 0x11,
      msg: "缴存"
    },
    {
      id: 0x22,
      msg: "購買BGT"
    },
    {
      id: 0x42,
      msg: "提取"
    },
    {
      id: 0x81,
      msg: "清算贖回"
    }
  ],
  2: [
    {
      id: 0x01,
      msg: "增加"
    },
    {
      id: 0x02,
      msg: "减少"
    },
    {
      id: 0x101,
      msg: "申购"
    },
    {
      id: 0x202,
      msg: "贖回"
    },
    {
      id: 0x401,
      msg: "結息"
    },
    {
      id: 0x402,
      msg: "贖回退回利息"
    },
    {
      id: 0x802,
      msg: "清算贖回"
    },
    {
      id: 0x1001,
      msg: "轉入"
    },
    {
      id: 0x1002,
      msg: "轉出"
    }
  ],
  3: [
    {
      id: 1,
      msg: "註冊"
    },
    {
      id: 4,
      msg: "划转额度"
    },
    {
      id: 8,
      msg: "邀請"
    },
    {
      id: 16,
      msg: "購買"
    }
  ]
};

const requestUrl = {
  1: RECORDS,
  2: BGT_HISTORY,
  3: CREDIT_HISTORY
};

const titleName = {
  1: "代幣明細",
  2: "BGT明細",
  3: "額度明細"
};

class FlowDetail extends Component {
  static navigationOptions = ({ navigation }) =>
    NavBarConfig(
      {
        headerTitle: () => (
          <TouchableOpacity
            onPress={() => {
              navigation.setParams({
                filterHidden: !navigation.state.params.filterHidden
              });
            }}
          >
            <Text
              style={{
                fontSize: 18,
                color: "#fff",
                fontWeight: "bold"
              }}
            >
              {titleName[navigation.state.params.type]}
              <Text
                style={{
                  fontSize: 14
                }}
              >
                {navigation.state.params.filterHidden ? "▲" : "▼"}
              </Text>
            </Text>
          </TouchableOpacity>
        ),
        headerRight: []
      },
      navigation
    );
  state = {
    pageNo: 0,
    list: [],
    totalPage: 0,
    isEditing: false,
    flags: null
  };

  handleChangeFlags(flags = 0) {
    this.setState({
      flags: flags
    });
    this.getNoticeList(true);
    this.handleChangeFilter();
  }
  async getNoticeList(flag = false) {
    if (flag) {
      await this.setState({
        pageNo: 0,
        list: [],
        totalPage: 0
      });
    }
    if (
      this.state.pageNo == this.state.totalPage &&
      this.state.pageNo > 0 &&
      !flag
    ) {
      return;
    }
    const params = {};
    if (this.state.flags) params.flags = this.state.flags;
    let data = await http.get(
      requestUrl[this.props.navigation.state.params.type],
      {
        page: this.state.pageNo,
        ...params
      }
    );

    let list = this.state.list.concat(data.data.list);
    if (flag) {
      list = data.data.list;
    }
    this.setState({
      pageNo: this.state.pageNo + 1,
      list: list,
      totalPage: Math.ceil(data.data.count / data.data.take)
    });
  }

  handleScrollBottom = e => {
    isScrollBottom(e, () => {
      this.getNoticeList();
    });
  };

  async componentWillMount() {
    await this.initQuery();
    this.getNoticeList();
  }

  // 初始化传参数
  async initQuery() {
    if (!this.props.navigation.state.params) return;
    await this.setState({
      flags: this.props.navigation.state.params.flags
    });
  }

  handleEditStatus() {
    this.setState({
      isEditing: !this.state.isEditing
    });
  }

  async handleChangeFilter() {
    const filterHidden = !this.props.navigation.state.params.filterHidden;
    this.props.navigation.setParams({
      filterHidden: filterHidden
    });
  }

  render() {
    return (
      <View style={flowDetailStyles.container}>
        {!this.props.navigation.state.params.filterHidden ? null : (
          <View style={flowDetailStyles.filterList}>
            <View style={flowDetailStyles.listUl}>
              <TouchableOpacity
                style={[flowDetailStyles.listUlLi]}
                onPress={() => this.handleChangeFlags()}
              >
                <Text
                  style={[
                    flowDetailStyles.listUlLiText,
                    !this.state.flags ? flowDetailStyles.liActive : {}
                  ]}
                >
                  全部
                </Text>
              </TouchableOpacity>
              {filters[this.props.navigation.state.params.type].map(
                (filter, index) => (
                  <TouchableOpacity
                    key={index}
                    style={[flowDetailStyles.listUlLi]}
                    onPress={() => {
                      this.handleChangeFlags(filter.id);
                    }}
                  >
                    <Text
                      style={[
                        flowDetailStyles.listUlLiText,
                        this.state.flags == filter.id
                          ? flowDetailStyles.liActive
                          : {}
                      ]}
                    >
                      {filter.msg}
                    </Text>
                  </TouchableOpacity>
                )
              )}
            </View>
          </View>
        )}

        <ScrollView onMomentumScrollEnd={this.handleScrollBottom.bind(this)}>
          <View style={flowDetailStyles.flowWater}>
            {this.state.list.map((item, index) => (
              <View style={flowDetailStyles.flowWaterItem} key={index}>
                <View style={flowDetailStyles.flowWaterTopOrBottom}>
                  <Text
                    style={[
                      flowDetailStyles.topSpan,
                      {
                        flex: 1
                      }
                    ]}
                  >
                    {`${
                      filters[this.props.navigation.state.params.type].find(
                        it => it.id == (item.reason || item.type)
                      ).msg
                    }`}
                  </Text>
                  <Text style={flowDetailStyles.topSpan}>
                    {this.props.navigation.state.params.type == 3
                      ? item.direction
                        ? "+"
                        : "-"
                      : ""}
                    {item.amount}
                  </Text>
                </View>
                <View style={flowDetailStyles.flowWaterTopOrBottom}>
                  <Text style={flowDetailStyles.bottomTime}>
                    {this.props.navigation.state.params.type == 2 ?moment(new Date(item.donetime)).utcOffset(new Date(item.donetime).getTimezoneOffset()).format("YYYY-MM-DD") : moment(new Date(item.createtime)).utcOffset(new Date(item.createtime).getTimezoneOffset()).format("YYYY-MM-DD")}
                  </Text>
                  <Text style={flowDetailStyles.bottomCount}>
                    {item.fee ? `手續費：${item.fee}` : ""}
                  </Text>
                </View>
              </View>
            ))}
          </View>
        </ScrollView>
      </View>
    );
  }
}

export default FlowDetail;
